
var edit_or_not=true
//区域选择
/*//全选全不选
function goodselection() {
    if($("#saleAreas").is(':checked')==true){
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = true;
        }
    }else {
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = false;
        }
    }

}*/
//子级选中
goodselectionall()
function goodselectionall() {
    var saleArea=$("input:checkbox[name='saleArea']")
    var saleArea2=$("input:checkbox[name='saleArea']:checked")
    if(saleArea2.length==saleArea.length){
        $("#saleAreas").prop("checked", true)
    }else {
        $("#saleAreas").prop("checked", false)
    }
}

var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
function operatesearch() {
    //区域选择
    var regionall=[]
    var regions=$("input:checkbox[name='saleArea']:checked")
    for (var i=0;regions.length>i;i++){
        regionall.push($(regions[i]).val())
    }
    $.ajax({
        url: root.touchscreen.findTouchScreenList,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":30,
            "companyName":$("#companyName").val(),
            "parentWarehouseIds":regionall,

        }),
        success: function (data) {
            couponlist1(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.touchscreen.findTouchScreenList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":30,
                            "companyName":$("#companyName").val(),
                            "parentWarehouseIds":regionall,

                        }),
                        success: function (result) {
                            couponlist1(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

// var j = 0;
function couponlist1(data, index){
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组
    var datashu =data.startRow+1;
    $.each(data.data, function (i, field) {
        var datashus = datashu++
        var rowData = new Array();
        rowData.push(field.companyName);
        rowData.push(field.partentWarehouseName);
        rowData.push(field.shopManager);
        rowData.push(field.managerPhone);
        rowData.push(field.status);
        rowData.push(field.createTime);
        rowData.push(field.updatePerson);
        rowData.push(datashus);
        rowData.push(field.id);
        dataSource.push(rowData);

    });

    initData(dataSource);

    function initData(dataSource) {

        var dttable = $('#tabletables').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#tabletables").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[4] == 10) {
                            val = '生效'
                        }else {
                            val = '失效'
                        }
                        return val;
                    },
                    "targets":5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":7
                },


                {
                    "render": function (data, type, row, meta) {
                        var val = '<span class="powerButton 587"><a onclick="modifyStore(\''+row[8]+'\')">修改</a></sapn>'
                        return val;
                    },
                    "targets":8
                },



            ]
        });
        //权限控制函数
        power()
    };
}
//区域
function salesArea(val,belongAreaIds,warehouseCodes) {
    $("#salesArea").html(" <option value=''>请选择销售区域</option>")
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url: root.sroreinter.queryWarehouseInfo,
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data: JSON.stringify({
            warehouseCode:""
        }),
        success: function (data) {
            console.log(val)
            if (val!=undefined) {
                console.log(data)
                for(var i=0;i<data.data.length;i++){
                    if(val==data.data[i].warehouseCode){
                        $("#salesArea").append("<option  value=" + data.data[i].warehouseCode + " selected>" + data.data[i].warehouseAliasName + "</option>")
                      
                    }else {
                        $("#salesArea").append("<option value=" + data.data[i].warehouseCode + ">" + data.data[i].warehouseAliasName + "</option>")

                    }

                }
                sellingpricearea(val,belongAreaIds,warehouseCodes)

            }else {
                for(var i=0;i<data.data.length;i++){
                    $("#salesArea").append("<option  value=" + data.data[i].warehouseCode + ">" + data.data[i].warehouseAliasName + "</option>")

                }
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//门店选择
function storeSelections(e) {
    if($(".addressTitle").html()=='编辑'){
        edit_or_not=false
    }else {
        edit_or_not=true
    }
    //根据门店查 省份

    seachporvinfn($("#storeSelection option:selected").attr('sendcompanyid'))
}
function seachporvinfn(sendCompanyId){
    $.ajax({
        url:root.sroreinter.getSonCompanyListBySendCompanyId,
        cache: false, //禁用缓存
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        type: "POST",
        data: {
            sendCompanyId: sendCompanyId,
        },
        success: function (data) {
            if(data.errorCode == 0){
            $("#selling_price_area").html("<option value=" + data.data.provinceCode + " selected disabled='disabled'> " + data.data.provinceName + "</option>") //  
        }
    },
        error: function () {

        }
    });
}
//根据中心仓 查 门店选择
function sellingpricearea(val,belongAreaIds,warehouseCodes) {
    if($(".addressTitle").html()=='编辑'&&val==1){
        edit_or_not=false
    }else {
        edit_or_not=true
    }

    $("#storeSelection").html(" <option value=''>请选择门店</option>")
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url: root.sroreinter.queryWarehouseInfo,
        cache: false, //禁用缓存
        type: "POST",
        dataType:"json",
        data: JSON.stringify({
             warehouseCode:""
        }),
        success: function (data) {
            // //售价区域
            // if(belongAreaIds!=undefined){
            //         for(var j=0;j<data.data.length;j++){
            //             if(belongAreaIds==data.data[j].provinceCode){
            //                 $("#selling_price_area").html("<option value=" + data.data[j].provinceCode + " selected disabled='disabled'>" + data.data[j].provinceName + "</option>")
            //             }
            //         }
            // }else {
            //     if($("#salesArea option:selected").val()!=""){
            //         for(var j=0;j<data.data.length;j++){
            //             if($("#salesArea option:selected").val()==data.data[j].warehouseCode){
            //                 $("#selling_price_area").html("<option value=" + data.data[j].provinceCode + " selected disabled='disabled'>" + data.data[j].provinceName + "</option>")
            //             }

            //         }
            //     }
            // }

            //门店选择
            if(warehouseCodes!=undefined){
                //修改
                    for(var k=0;k<data.data.length;k++){
                        if($("#salesArea option:selected").val()==data.data[k].warehouseCode){
                            if(warehouseCodes==data.data[k].warehouseCode){
                                $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+" value=" + data.data[k].warehouseCode + " selected>" + data.data[k].selfMentionPointName + "</option>")

                            }else {
                                $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+"  value=" + data.data[k].warehouseCode + ">" + data.data[k].selfMentionPointName + "</option>")

                            }
                            for(var n=0;n<data.data[k].childWarehouses.length;n++) {
                                if(warehouseCodes==data.data[k].childWarehouses[n].warehouseCode){

                                 $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+" value=" + data.data[k].childWarehouses[n].warehouseCode + " selected>" + data.data[k].childWarehouses[n].selfMentionPointName + "</option>")

                                }else {
                                    $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+" value=" + data.data[k].childWarehouses[n].warehouseCode + " >" + data.data[k].childWarehouses[n].selfMentionPointName + "</option>")


                                }
                            }


                        }

                    }
                    seachporvinfn($("#storeSelection option:selected").attr('sendcompanyid'))
            }else {
                //新增
                if($("#salesArea option:selected").val()!=""){
                    for(var k=0;k<data.data.length;k++){
                        if($("#salesArea option:selected").val()==data.data[k].warehouseCode){
                            $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+"  value=" + data.data[k].warehouseCode + ">" + data.data[k].selfMentionPointName + "</option>")
                            if(data.data[k].childWarehouses!=""){
                                for(var n=0;n<data.data[k].childWarehouses.length;n++) {
                                    $("#storeSelection").append("<option sendCompanyId="+data.data[k].sendCompanyId+" value=" + data.data[k].childWarehouses[n].warehouseCode + " >" + data.data[k].childWarehouses[n].selfMentionPointName + "</option>")
                                }
                            }

                        }

                    }
                }
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

//新增
function addstore() {
    $("#store").modal("show");
    $(".addressTitle").html("新建");
    $("#viewIinksbutton").css({
        display: "none"
    });
    //获取区域
    salesArea()
    //清空
    $("#shopManager").val('')
    $("#managerPhone").val('')
    $("#salesArea").html("<option value=''>请选择中心仓</option>")
    $("#selling_price_area").html("<option value=''>请选择价格省份</option>")
    $("#storeSelection").html(" <option value=''>请选择门店</option>")
    $('select').val('');
    $("input[name=effectiveStatus]")[0].checked=true
    $("input[name=effectiveStatus]:checked").val(10)
}
//取消
function close_model(val) {
    if(val==1){
        $("#store").modal("hide");
    }else {
        var curInd = layer.confirm(
            '<span>确认取消则不保留编辑信息</span>'+'<br/>', {offset:'230px',title:'提示',btn: ['确定', '取消']},
            function(index){

                $("#store").modal("hide");
                layer.close(curInd);

            },function(){
                layer.close(curInd);

            });
    }



}
var links=""
//修改
function modifyStore(ids) {
    $("#store").modal("show");
    $(".addressTitle").html("编辑");
    $("#viewIinksbutton").css({
        display: "inline"
    });
    $.ajax({
        url: root.touchscreen.findTouchScreenMsg,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            id: ids
        }),
        success: function (data) {
            if(data.errorCode==0){
                var datas=data.data
                //获取区域
                salesArea(datas.parentWarehouseId,datas.provinceCode,datas.warehouseId)
                $("#shopManager").val(datas.shopManager)
                $("#managerPhone").val(datas.managerPhone)
                if(datas.status==10){
                    $("input[name=effectiveStatus]")[0].checked=true
                    $("input[name=effectiveStatus]:checked").val(datas.status)
                }else {
                    $("input[name=effectiveStatus]")[1].checked=true
                    $("input[name=effectiveStatus]:checked").val(datas.status)
                }
                $("#storeid").val(datas.id)
                links=datas.screenUrl

            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

}
//保存
function preservation() {
    if($("#salesArea option:selected").val()=="" || $("#selling_price_area option:selected").val()=="" || $("#storeSelection option:selected").val()==""){
        layer.msg('请完善必填信息', {icon: 5,time:1000});
        return false;
    }
    if($(".addressTitle").html()=='新建'){
        $.ajax({
            url:root.touchscreen.addTouchScreen,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            contentType: "application/json",
            data: JSON.stringify({
                "parentWarehouseId":$("#salesArea option:selected").val(),
                "partentWarehouseName":$("#salesArea option:selected").text(),
                "saleAreaId":'0',
                "warehouseId":$("#storeSelection option:selected").val(),
                "companyName":$("#storeSelection option:selected").text(),
                "shopManager":$("#shopManager").val(),
                "managerPhone":$("#managerPhone").val(),
                "status": $("input[name=effectiveStatus]:checked").val(),
                "updatePerson":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
            }),
            success: function (data) {
                if(data.errorCode==0){

                    layer.msg('保存成功', {icon: 6,time:1000});
                    setTimeout( function () {
                        $("#viewIinks").modal("show");
                        $("#newPath").val(data.data)
                    },1000);

                    operatesearch()
                }else {
                    $.Huimodalalert(data.msg,2000);
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }else {
        $.ajax({
            url: root.touchscreen.updateTouchScreen,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            contentType: "application/json",
            data: JSON.stringify({
                "parentWarehouseId":$("#salesArea option:selected").val(),
                "partentWarehouseName":$("#salesArea option:selected").text(),
                "saleAreaId":'0',
                "warehouseId":$("#storeSelection option:selected").val(),
                "companyName":$("#storeSelection option:selected").text(),
                "shopManager":$("#shopManager").val(),
                "managerPhone":$("#managerPhone").val(),
                "status": $("input[name=effectiveStatus]:checked").val(),
                "updatePerson":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                "id":$("#storeid").val()
            }),
            success: function (data) {
                if(data.errorCode==0){
                    if( edit_or_not==false){
                        var curInd = layer.confirm(
                            '<span>\n' +
                            '您已更新店面触摸屏链接地址，请将【门店触摸屏链接】地址更新，否则将会影响正常使用</span>'+'<br/>', {title:'门店触摸屏更改提示',btn: ['确定']},
                            function(index){
                                $("#store").modal("hide");
                                layer.close(curInd);

                            },function(){
                                layer.close(curInd);

                            });
                    }else {
                        layer.msg('编辑成功', {icon: 6,time:1000});
                        setTimeout( function () {
                            $("#store").modal("hide");
                        },1000);
                    }
                    operatesearch()
                }else {
                    $.Huimodalalert(data.msg,2000);
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }


}

//链接关闭按钮
function closes() {
    if($(".addressTitle").html()=='新建'){
        $("#store").modal("hide");
    }else {
        $("#viewIinks").modal("hide");
    }
}
//查看链接
function viewIinks() {
    $("#viewIinks").modal("show");
    $("#newPath").val(links)
}
//复制链接
function copyIink() {
    var Url=document.getElementById("newPath");
    Url.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    layer.msg('复制成功', {icon: 6,time:1000});
}